package auth_service

import (
	"encoding/json"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/tealeg/xlsx"
	"io"
	"models"
	"pkg/e"
	"pkg/export"
	"pkg/gredis"
	"pkg/logging"
	"service/cache_service"
	"strconv"
	"time"
)

type Auth struct {
	ID         int
	Username   string
	Password   string
	Mobile     string
	ModifiedBy string

	PageNum  int
	PageSize int
}

func (a *Auth) getMaps() map[string]interface{} {
	maps := make(map[string]interface{})
	maps["deleted_on"] = 0
	return maps
}

// 分页列表统计
func (a *Auth) Count() (int, error) {
	return models.GetAuthsTotal(a.getMaps())
}

// 分页列表
func (a *Auth) GetAll() ([]*models.Auth, error) {
	var (
		auths, cacheAuths []*models.Auth
	)

	// 查缓存
	cache := cache_service.Auth{
		PageNum:  a.PageNum,
		PageSize: a.PageSize,
	}
	key := cache.GetAuthsKey()
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logging.Error(err)
		} else {
			json.Unmarshal(data, &cacheAuths)
			return cacheAuths, nil
		}
	}

	// 查库
	auths, err := models.GetAuths(a.PageNum, a.PageSize, a.getMaps())
	if err != nil {
		return nil, err
	}

	// 存缓存
	gredis.Set(key, auths, 3600)
	return auths, nil
}

// 登录校验
func (a *Auth) Check() (bool, int, error) {
	return models.CheckAuth(a.Username, a.Password)
}

// 新增
func (a *Auth) Add() (int, error) {
	// 删缓存
	gredis.LikeDeletes(e.CACHE_AUTH)

	auth := map[string]interface{}{
		"username": a.Username,
		"password": a.Password,
		"mobile":   a.Mobile,
	}
	id, err := models.AddAuth(auth)
	if err != nil {
		return -1, err
	}
	return id, nil
}

// 验证id是否存在
func (a *Auth) ExistAuthByID() (bool, error) {
	return models.ExistAuthByID(a.ID)
}

// 根据id查询账号
func (a *Auth) Get() (*models.Auth, error) {
	// 查缓存
	var cacheAuth *models.Auth
	cache := cache_service.Auth{
		ID: a.ID,
	}
	key := cache.GetAuthKey()
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logging.Error(err)
		} else {
			json.Unmarshal(data, &cacheAuth)
			return cacheAuth, nil
		}
	}

	// 查库
	auth, err := models.GetAuth(a.ID)
	if err != nil {
		return nil, err
	}

	// 存缓存
	gredis.Set(key, auth, 3600)
	return auth, nil
}

// 修改
func (a *Auth) Edit() error {
	// 删缓存
	gredis.LikeDeletes(e.CACHE_AUTH)

	auth := map[string]interface{}{
		"password":    a.Password,
		"mobile":      a.Mobile,
		"modified_by": a.ModifiedBy,
	}
	return models.EditAuth(a.ID, auth)
}

// 删除
func (a *Auth) Delete() error {
	// 删缓存
	gredis.LikeDeletes(e.CACHE_AUTH)
	return models.DeleteAuth(a.ID)
}

// 导出
func (a *Auth) Export() (string, error) {
	auths, err := a.GetAll()
	if err != nil {
		return "", err
	}

	file := xlsx.NewFile()
	sheet, err := file.AddSheet("账号")
	if err != nil {
		return "", err
	}

	// 标题
	titles := []string{
		"ID",
		"用户名",
		"密码",
		"手机号",
		"创建时间",
		"修改时间",
	}
	row := sheet.AddRow()

	// 标题添加列
	var cell *xlsx.Cell
	for _, title := range titles {
		cell = row.AddCell()
		cell.Value = title
	}

	// 添加数据
	for _, v := range auths {
		values := []string{
			strconv.Itoa(v.ID),
			v.Username,
			v.Password,
			v.Mobile,
			v.CreatedOn,
			v.ModifiedOn,
		}

		row = sheet.AddRow()
		for _, value := range values {
			cell = row.AddCell()
			cell.Value = value
		}
	}

	time := strconv.Itoa(int(time.Now().Unix()))
	filename := "auth-" + time + e.Xlsx

	fullPath := export.GetExcelFullPath() + filename
	err = file.Save(fullPath)
	if err != nil {
		return "", err
	}
	return filename, nil
}

// 导入
func (a *Auth) Import(r io.Reader) error {
	xlsx, err := excelize.OpenReader(r)
	if err != nil {
		return err
	}

	rows, err := xlsx.GetRows("账号")
	if err != nil {
		return err
	}
	for irow, row := range rows {
		if irow > 0 {
			var data []string
			for _, cell := range row {
				data = append(data, cell)
			}
			logging.Debug("Import excel: %v", data)
		}
	}
	return nil
}
